import jsQR from "jsqr"

export const scanQrCode = (file, callback) => {
    const image = new Image()
    image.src = file
    image.addEventListener("load", (e) => {
        console.log(
            "image on load, image.naturalWidth, image.naturalHeight",
            image.naturalWidth,
            image.naturalHeight
        )

        const canvas = document.createElement("canvas") // Creates a canvas object
        canvas.width = image.naturalWidth // Assigns image's width to canvas
        canvas.height = image.naturalHeight // Assigns image's height to canvas

        const context = canvas.getContext("2d") // Creates a contect object
        context.imageSmoothingEnabled = false
        context.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight) // Draws the image on canvas

        const imageData = context.getImageData(0, 0, image.naturalWidth, image.naturalHeight) // Assigns image base64 string in jpeg format to a variable
        const code = jsQR(imageData.data, image.naturalWidth, image.naturalHeight)

        if (code) {
            console.log("Found QR code", code)

            callback(code)
        }
    })
}